package com.iasku.iaskueleclass_phone.activity;

import java.util.ArrayList;
import java.util.List;

import javax.crypto.spec.IvParameterSpec;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.iasku.constant.Constant;
import com.iasku.constant.IntentConfig;
import com.iasku.entity.Point;
import com.iasku.entity.Rectangle;
import com.iasku.iaskueleclass_phone.R;
import com.iasku.iaskueleclass_phone.ReturnData;
import com.iasku.iaskueleclass_phone.Status;
import com.iasku.manager.DataManager;
import com.iasku.manager.IDataManager;

/**
 * 错题本已订正
 */
public class ErrorBookQuestionCorrectedAnswerActivity extends BaseActivity {
    private static final int TASK_GET_PIC = 1;

    private ImageView mImgv;
    private ImageButton mPrevBtn, mNextBtn;
    private String mAnswerid;
    private int mPageno;
    private Bitmap mCurBitmap;
    private String[] mCommandArr;
    private Bitmap[] mPicimg;
    private Bitmap[] mBgnimg;
    private int mPic_w, mPic_h;
    private float mPic_w_scale_read, mPic_h_scale_read;
    private int pencolor, g_penWidth = 2;
    private int c_purple;
    private int g_penDash = 0;
    private List<Point> points = new ArrayList<Point>();
    private ArrayList<Rectangle> rects = new ArrayList<Rectangle>();

    private void setupView() {
        mImgv = (ImageView) findViewById(R.id.iv_answer_img);
        mPrevBtn = (ImageButton) findViewById(R.id.iv_answer_previous);
        mNextBtn = (ImageButton) findViewById(R.id.iv_answer_next);
    }

    private void addListener() {
        MyOnClickListener mListener = new MyOnClickListener();
        mPrevBtn.setOnClickListener(mListener);
        mNextBtn.setOnClickListener(mListener);
    }

    private void initView() {
        setupView();
        addListener();
        String attach = getIntent().getStringExtra(IntentConfig.ANSWER_ATTACH);
        c_purple = getResources().getColor(R.color.purple);
        mPageno = 0;
        try {
            JSONArray mJSONArray = new JSONArray(attach);
            int length = mJSONArray.length();
            mCommandArr = new String[length];
            mPicimg = new Bitmap[length];
            mBgnimg = new Bitmap[length];
            mAnswerid = mJSONArray.getJSONObject(0).optString("answerid");
            mBarCenterTitleTv.setText("第" + (mPageno + 1) + "页，共" + length + "页");
            for (int i = 0; i < mJSONArray.length(); i++) {
                JSONObject attachJSON = mJSONArray.getJSONObject(i);
                mCommandArr[i] = attachJSON.optString("cmdtext");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        setButtonStatus();
        if (mPicimg[mPageno] == null) {
            startTask(TASK_GET_PIC);
        } else {
            mImgv.setImageBitmap(mPicimg[mPageno]);
        }
    }

    @Override
    protected void onCreate(Bundle saveInstance) {
        super.onCreate(saveInstance);
        setContentView(R.layout.homework_answer_submitorcorrected);
        initTitleBar();
        initView();
    }

    @Override
    public int startTask(int taskId) {
        if (taskId == TASK_GET_PIC) {
            mProgressDialog.setMessage("正在加载...");
            mProgressDialog.show();
        }
        return super.startTask(taskId);
    }

    @Override
    public Status onTaskInBackground(int taskId, Bundle bundle) {
        switch (taskId) {
        case TASK_GET_PIC: {
            String loadPath = Constant.SERVERURL + Constant.DATA_UPLOAD + mAnswerid + "_" + (mPageno + 1) + ".jpg";
            IDataManager manager = DataManager.getInstance();
            ReturnData<Bitmap> mReturnData = manager.loadSubmitImage(this, loadPath, mAnswerid);
            mCurBitmap = mReturnData.getData();
            return new Status(mReturnData);
        }
        }
        return super.onTaskInBackground(taskId, bundle);
    }

    @Override
    public int onTaskComplete(int taskId, Status status) {
        switch (taskId) {
        case TASK_GET_PIC: {
            getImageOk();
        }
            break;
        }

        return super.onTaskComplete(taskId, status);
    }

    private void getImageOk() {
        mProgressDialog.dismiss();
        Bitmap bmp = Bitmap.createScaledBitmap(mCurBitmap, mImgv.getWidth(), mImgv.getHeight(), false);
        mPicimg[mPageno] = Bitmap.createScaledBitmap(bmp, mImgv.getWidth(), mImgv.getHeight(), false).copy(
                Config.ARGB_8888, true);
        mBgnimg[mPageno] = Bitmap.createScaledBitmap(bmp, mImgv.getWidth(), mImgv.getHeight(), false).copy(
                Config.ARGB_8888, true);
        mPic_w = mPicimg[mPageno].getWidth();
        mPic_h = mPicimg[mPageno].getHeight();
        mPic_w_scale_read = mPic_w / 800f;
        mPic_h_scale_read = mPic_h / 600f;
        if (mCommandArr[mPageno] != null && !"".equals(mCommandArr[mPageno]) && !"null".equals(mCommandArr[mPageno])) {
            String[] arr = mCommandArr[mPageno].split("#");
            for (int i = 0; i < arr.length; i++) {
                exeCommand(arr[i]);
            }
        }
        mImgv.setImageBitmap(mPicimg[mPageno]);
    }

    private void setPen(String ss) {
        String[] spen = ss.split(":");
        g_penWidth = Integer.parseInt(spen[1]);
        // Toast.makeText(ClassShow.this, ss,Toast.LENGTH_SHORT).show();
        pencolor = Integer.parseInt(spen[2]);
        switch (Integer.parseInt(spen[2])) {
        case 1:
            pencolor = Color.RED;
            break;
        case 2:
            pencolor = Color.BLUE;
            break;
        case 3:
            pencolor = c_purple;
            break;
        case 4:
            pencolor = Color.BLACK;
            break;
        case 5:
            pencolor = Color.YELLOW;
            break;
        default:
            pencolor = Color.RED;// android端传递的颜色int值
            break;
        }

        switch (Integer.parseInt(spen[3])) {
        case 1:
            g_penDash = 0;
            break;
        case 2:
            g_penDash = 1;
            break;
        case 3:
            g_penDash = 2;
            break;
        case 4:
            g_penDash = 3;
            // g_penDash = DashStyle.DashDotDot ;
            break;
        }
    }

    private void exeCommand(String displaytxt) {
        Canvas cv = null;

        Paint p = new Paint();
        p.setColor(pencolor);
        p.setStyle(Paint.Style.STROKE);
        p.setStrokeWidth(g_penWidth);
        p.setAntiAlias(true);

        float x1, y1, x2, y2;

        if (displaytxt.startsWith("SetPen")) {
            setPen(displaytxt.substring(6, displaytxt.indexOf(";")));
            p.setColor(pencolor);
            p.setStrokeWidth(g_penWidth);
            if (g_penDash == 0)
                p.setPathEffect(null);
            else if (g_penDash == 1)
                p.setPathEffect(new DashPathEffect(new float[] { 8, 2, 8, 2 }, 1));
            else if (g_penDash == 2)
                p.setPathEffect(new DashPathEffect(new float[] { 12, 2, 3, 2 }, 1));
            displaytxt = displaytxt.substring(displaytxt.indexOf(";") + 1);

        }
        if (displaytxt.startsWith("Pen:")) {
            p.setPathEffect(null);
            String[] pen = displaytxt.split(":");
            points.clear();
            for (int i = 0; i < pen.length / 2; i++) {
                Point a = new Point(Float.parseFloat(pen[i * 2 + 1]) * mPic_w_scale_read,
                        Float.parseFloat(pen[i * 2 + 2]) * mPic_h_scale_read);
                points.add(a);
            }
            cv = new Canvas(mPicimg[mPageno]);
            for (int i = 0; i < points.size() - 1; i++) {
                Point pp = points.get(i);
                Point pp1 = points.get(i + 1);
                cv.drawLine(pp.getX(), pp.getY(), pp1.getX(), pp1.getY(), p);
            }
            cv.save(Canvas.ALL_SAVE_FLAG);// 保存

            points.clear();

        } else if (displaytxt.startsWith("Erase:")) {
            String[] pen = displaytxt.split(":");
            rects.clear();
            for (int i = 0; i < pen.length / 4; i++) {
                Rectangle a = new Rectangle();
                a.setX((int) (Float.parseFloat(pen[i * 4 + 1]) * mPic_w_scale_read));
                a.setY((int) (Float.parseFloat(pen[i * 4 + 2]) * mPic_h_scale_read));
                a.setWidth((int) (Float.parseFloat(pen[i * 4 + 3])));
                a.setHeight((int) (Float.parseFloat(pen[i * 4 + 4])));
                rects.add(a);
            }
            cv = new Canvas(mPicimg[mPageno]);

            Bitmap sclone = null;
            for (int i = 0; i < rects.size(); i++) {
                Rectangle rc = rects.get(i);
                if (mBgnimg[mPageno] != null) {
                    sclone = Bitmap.createBitmap(mBgnimg[mPageno], rc.getX(), rc.getY(), rc.getWidth(), rc.getHeight());
                    cv.drawBitmap(sclone, rc.getX(), rc.getY(), p);
                }
            }
            cv.save(Canvas.ALL_SAVE_FLAG);
            rects.clear();
            if (sclone != null)
                sclone.recycle();

        } else if (displaytxt.startsWith("ClearScreen")) {

            mPicimg[mPageno] = Bitmap.createBitmap(mBgnimg[mPageno]);
        } else if (displaytxt.startsWith("Line:")) {
            String[] pen = displaytxt.split(":");

            x1 = Integer.parseInt(pen[1]) * mPic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * mPic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * mPic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * mPic_h_scale_read;

            cv = new Canvas(mPicimg[mPageno]);
            cv.drawLine(x1, y1, x2, y2, p);
            cv.save(Canvas.ALL_SAVE_FLAG);

        } else if (displaytxt.startsWith("Rectangle:")) {
            String[] pen = displaytxt.split(":");
            x1 = Float.parseFloat(pen[1]) * mPic_w_scale_read;
            y1 = Float.parseFloat(pen[2]) * mPic_h_scale_read;
            x2 = Float.parseFloat(pen[3]) * mPic_w_scale_read;
            y2 = Float.parseFloat(pen[4]) * mPic_h_scale_read;
            Rect rc1 = new Rect();
            rc1.left = (int) x1;
            rc1.right = (int) x2;
            rc1.top = (int) y1;
            rc1.bottom = (int) y2;
            cv = new Canvas(mPicimg[mPageno]);
            cv.drawRect(rc1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Ellipse:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * mPic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * mPic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * mPic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * mPic_h_scale_read;
            RectF rc1 = new RectF();
            rc1.left = x1;
            rc1.right = x2;
            rc1.top = y1;
            rc1.bottom = y2;
            cv = new Canvas(mPicimg[mPageno]);
            cv.drawOval(rc1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Circle:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * mPic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * mPic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * mPic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * mPic_h_scale_read;
            float radius = (float) (Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)));
            cv = new Canvas(mPicimg[mPageno]);
            cv.drawCircle(x1, y1, radius, p);
            cv.drawCircle(x1, y1, 1, p);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Arrow:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * mPic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * mPic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * mPic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * mPic_h_scale_read;
            cv = new Canvas(mPicimg[mPageno]);
            drawArrow(cv, p, x1, y1, x2, y2);
            cv.save(Canvas.ALL_SAVE_FLAG);
        } else if (displaytxt.startsWith("Ten:")) {
            String[] pen = displaytxt.split(":");
            x1 = Integer.parseInt(pen[1]) * mPic_w_scale_read;
            y1 = Integer.parseInt(pen[2]) * mPic_h_scale_read;
            x2 = Integer.parseInt(pen[3]) * mPic_w_scale_read;
            y2 = Integer.parseInt(pen[4]) * mPic_h_scale_read;
            cv = new Canvas(mPicimg[mPageno]);
            drawTen(cv, p, x1, y1, x2, y2);
            cv.save(Canvas.ALL_SAVE_FLAG);
        }
    }

    private void drawTen(Canvas g, Paint p, float x1, float y1, float x2, float y2) {
        drawArrow(g, p, x1 - (x2 - x1) / 6, y1, x2, y1);
        drawArrow(g, p, x1, y1 - (y2 - y1) / 6, x1, y2);
    }

    private void drawArrow(Canvas g, Paint p, float x1, float y1, float x2, float y2) {
        float pw = (float) g_penWidth;
        double arrowlen = 10 * pw;
        double arc = 10 * Math.PI / 180;
        double x3, y3, x4, y4, x5, y5, len;
        len = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
        if (x2 == x1) {
            if (y2 > y1 + arrowlen) {
                y5 = y2 - ((pw - 1) / 2) / Math.tan(arc);
                x5 = x2;
                y3 = y2 - arrowlen * Math.cos(arc);
                y4 = y3;
                x3 = x2 - arrowlen * Math.sin(arc);
                x4 = x2 + arrowlen * Math.sin(arc);
            } else if (y2 + arrowlen < y1) {
                y3 = y2 + arrowlen * Math.cos(arc);
                y4 = y3;
                x3 = x2 - arrowlen * Math.sin(arc);
                x4 = x2 + arrowlen * Math.sin(arc);
                y5 = y2 + ((pw - 1) / 2) / Math.tan(arc);
                x5 = x2;
            } else {
                y3 = y2;
                y4 = y1;
                x3 = x2;
                x4 = x1;
                y5 = y2;
                x5 = x2;
            }
        } else if (x2 > x1) {
            if (y2 > y1) {
                y3 = y2 - arrowlen * Math.cos(Math.asin((x2 - x1) / len) - arc);
                y4 = y2 - arrowlen * Math.cos(Math.asin((x2 - x1) / len) + arc);
                x3 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) - arc);
                x4 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) + arc);
            } else if (y2 < y1) {
                y3 = y2 + arrowlen * Math.cos(Math.asin((x2 - x1) / len) - arc);
                y4 = y2 + arrowlen * Math.cos(Math.asin((x2 - x1) / len) + arc);
                x3 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) - arc);
                x4 = x2 - arrowlen * Math.sin(Math.asin((x2 - x1) / len) + arc);
            } else {
                x3 = x2 - arrowlen * Math.cos(arc);
                x4 = x3;
                y3 = y2 - arrowlen * Math.sin(arc);
                y4 = y2 + arrowlen * Math.sin(arc);
            }
            x5 = x2 - (((pw - 1) / 2) / Math.tan(arc)) * (x2 - x1) / len;
            y5 = y2 - (((pw - 1) / 2) / Math.tan(arc)) * (y2 - y1) / len;
        } else {
            if (y2 > y1) {
                y3 = y2 - arrowlen * Math.cos(Math.asin((x1 - x2) / len) - arc);
                y4 = y2 - arrowlen * Math.cos(Math.asin((x1 - x2) / len) + arc);
                x3 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) - arc);
                x4 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) + arc);

            } else if (y2 < y1) {
                y3 = y2 + arrowlen * Math.cos(Math.asin((x1 - x2) / len) - arc);
                y4 = y2 + arrowlen * Math.cos(Math.asin((x1 - x2) / len) + arc);
                x3 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) - arc);
                x4 = x2 + arrowlen * Math.sin(Math.asin((x1 - x2) / len) + arc);
            } else {
                x3 = x2 + arrowlen * Math.cos(arc);
                x4 = x3;
                y3 = y2 - arrowlen * Math.sin(arc);
                y4 = y2 + arrowlen * Math.sin(arc);
            }
            x5 = x2 - (((pw - 1) / 2) / Math.tan(arc)) * (x2 - x1) / len;
            y5 = y2 - (((pw - 1) / 2) / Math.tan(arc)) * (y2 - y1) / len;

        }
        p.setStyle(Paint.Style.FILL);
        Path path = new Path();
        path.moveTo(x2, y2);
        path.lineTo((float) x3, (float) y3);
        path.lineTo((float) x4, (float) y4);
        path.close();
        g.drawPath(path, p);
        p.setStyle(Paint.Style.STROKE);
        g.drawLine(x1, y1, (float) x5, (float) y5, p);
    }

    private class MyOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.iv_answer_previous:
                previous();
                break;

            case R.id.iv_answer_next:
                next();
                break;
            }
        }

        private void previous() {
            mPageno--;
            setPicImg();
        }

        private void next() {
            mPageno++;
            setPicImg();
        }

        private void setPicImg() {
            setButtonStatus();
            mBarCenterTitleTv.setText("第" + (mPageno + 1) + "页，共" + mPicimg.length + "页");
            if (mPicimg[mPageno] == null) {
                startTask(TASK_GET_PIC);
            } else {
                mImgv.setImageBitmap(mPicimg[mPageno]);
            }
        }
    }
    
    private void setButtonStatus(){
        mPrevBtn.setVisibility(View.VISIBLE);
        mNextBtn.setVisibility(View.VISIBLE);
        if (mPicimg.length == 1) {
            mPrevBtn.setVisibility(View.GONE);
            mNextBtn.setVisibility(View.GONE);
        } else {
            if (mPageno == 0) {
                mPrevBtn.setVisibility(View.GONE);
            } else if (mPageno == mPicimg.length - 1) {
                mNextBtn.setVisibility(View.GONE);
            }
        }
    }
    
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        release();
    }
    
    private void release(){
        if(mBgnimg != null && mBgnimg.length > 0){
            for (int i=0;i< mBgnimg.length;i++){
                if(mBgnimg[i] != null){
                    mBgnimg[i].recycle();
                    mBgnimg[i] = null;
                }
            }
            mBgnimg = null;
        }
        
        if(mPicimg != null && mPicimg.length > 0){
            for (int i=0;i< mPicimg.length;i++){
                if(mPicimg[i] != null){
                    mPicimg[i].recycle();
                    mPicimg[i] = null;
                }
            }
            mPicimg = null;
        }
    }
}
